/* 
 * Copyright 2014 ShangDao.Ltd  All rights reserved.
 * SiChuan ShangDao.Ltd PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * @ActMyDatum.java  2014-9-11 下午3:53:22 - Carson
 * @author Guzhu
 * @email:muyi126@163.com
 * @version 1.0
 */

package com.android.tiango.baba.act;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaBaseActivity;
import com.android.tiango.baba.adapter.DatumTagAdapter;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.entity.BaseEntity;
import com.android.tiango.baba.entity.UserInfoEntity;
import com.android.tiango.baba.entity.UserModel;
import com.android.tiango.baba.entity.UserTagEntity;
import com.android.tiango.baba.entity.UserTagModel;
import com.android.tiango.baba.util.CommUtil;
import com.android.tiango.baba.util.Constants;
import com.android.tiango.baba.util.DateAlertUtil;
import com.android.tiango.baba.util.DensityUtil;
import com.android.tiango.baba.util.ImageLoader;
import com.android.tiango.baba.util.StringUtils;
import com.android.tiango.baba.util.ToastUtils;
import com.android.tiango.baba.view.AppTitleBar;
import com.android.tiango.baba.view.MeasureGridView;
import com.android.tiango.baba.view.RoundImageView;

/**
 * 我的资料
 * 
 * @author YW_pc
 * 
 */
public class ActMyDatum extends BaBaseActivity implements OnClickListener {
	private RoundImageView iv_photo;
	private MeasureGridView ml_listview;
	private ImageView iv_more;
	private TextView tv_name;
	private TextView tv_email;
	private TextView tv_man;
	private TextView tv_girl;
	private TextView tv_brothday;
	private LinearLayout ll_sina;
	private TextView tv_sinabing;
	private LinearLayout ll_qq;
	private TextView tv_qqbing;
	private TextView tv_type;
	private TextView tv_num;
	private DatumTagAdapter adapter;
	private LinearLayout mLayout;
	private UserModel model;
	private String mTagsArray = "";
	private int gender = 0;
	private SharedPreferences mPreferences;
	private PopupWindow mPopupWindow;
	private WindowManager.LayoutParams mWL;
	private int mScreenWidth;
	private LinearLayout mLl_datesbrot;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.layout_mydatum);
		initView();
	}

	private void initView() {
		mWL = getWindow().getAttributes();
		mPreferences = getSharedPreferences(Constants.ShARED_NAME, Context.MODE_PRIVATE);
		mTitleBar = (AppTitleBar) findViewById(R.id.titlebar);
		mLayout = (LinearLayout) findViewById(R.id.ll_hotword);
		mLayout.setOnClickListener(this);
		iv_photo = (RoundImageView) findViewById(R.id.iv_photo);
		ml_listview = (MeasureGridView) findViewById(R.id.ml_listview);

		iv_more = (ImageView) findViewById(R.id.iv_more);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_email = (TextView) findViewById(R.id.tv_email);
		tv_man = (TextView) findViewById(R.id.tv_man);
		tv_girl = (TextView) findViewById(R.id.tv_girl);
		tv_man.setOnClickListener(this);
		tv_girl.setOnClickListener(this);
		iv_photo.setOnClickListener(this);
		tv_brothday = (TextView) findViewById(R.id.tv_brothday);
		ll_sina = (LinearLayout) findViewById(R.id.ll_sina);
		tv_sinabing = (TextView) findViewById(R.id.tv_sinabing);
		ll_qq = (LinearLayout) findViewById(R.id.ll_qq);
		tv_qqbing = (TextView) findViewById(R.id.tv_qqbing);
		tv_type = (TextView) findViewById(R.id.tv_type);
		tv_num = (TextView) findViewById(R.id.tv_num);
		mLl_datesbrot = (LinearLayout) findViewById(R.id.ll_datesbrot);
		mLl_datesbrot.setOnClickListener(this);
		if (null != mTitleBar) {
			mTitleBar.setTitle("我的资料");
			mTitleBar.setImageBackGround(R.drawable.bg_title_blue);
			mTitleBar.setBackIcon(R.drawable.icon_back);
			mTitleBar.setMoreText("保存");
			mTitleBar.setMoreTextOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (StringUtils.isEmpty(tv_brothday.getText().toString())) {
						model.setBirthday("");
					}
					if (StringUtils.isEmpty(tv_name.getText().toString())) {
						Toast.makeText(ActMyDatum.this, "输入昵称无效", Toast.LENGTH_LONG).show();
					} else if (!CommUtil.checkEmail(tv_email.getText().toString())) {
						Toast.makeText(ActMyDatum.this, "输入的邮箱无效", Toast.LENGTH_LONG).show();
					} else {
						if(model!=null && model.getUserTags()!=null){
							ArrayList<UserTagModel> al =	model.getUserTags();
							mTagsArray = "";
							for (UserTagModel userTagModel : al) {
								//激活
								if(userTagModel.getIsActivated() == 1){
									mTagsArray += userTagModel.getTagId() + ",";
								}
							}
							if(!StringUtils.isEmpty(mTagsArray)){
								mTagsArray = mTagsArray.substring(0, mTagsArray.length() - 1);
							}
						}
						doUserUp();
					}
				}
			});
			mTitleBar.setBackOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					setBack();
				}
			});
		}
		if (ShareCookie.isLoginAuth()) {
			model = ShareCookie.getUserInfo();
			setVal();
		}
	}
 
	private void setBack() {
		/**
		 * if(!StringUtils.isEmpty(mArray)){ String[] args = mArray.split(","); for (String key : args) { if(isClean(key) != -1){ Editor
		 * editor = mPreferences.edit(); editor.putInt(key, -1); editor.commit(); } } }
		 */
		setResult(200, new Intent());
		finish();
	}

	private String isClean(String key) {
		return mPreferences.getString(key, "");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setBack();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_hotword:
			startActivityForResult(new Intent(ActMyDatum.this, ActHotWord.class), 100);
			break;
		case R.id.tv_man:
			gender = 1;
			tv_man.setBackgroundResource(R.drawable.bg_sex_man_select);
			tv_man.setTextColor(getResources().getColor(R.color.font_white));
			tv_girl.setBackgroundResource(R.drawable.bg_sex_woman);
			tv_girl.setTextColor(getResources().getColor(R.color.font_red));
			break;
		case R.id.tv_girl:
			gender = 2;
			tv_man.setBackgroundResource(R.drawable.bg_sex_man);
			tv_man.setTextColor(getResources().getColor(R.color.c_blue2));
			tv_girl.setBackgroundResource(R.drawable.bg_sex_woman_select);
			tv_girl.setTextColor(getResources().getColor(R.color.font_white));
			break;
		case R.id.iv_photo:
			// 点击头像
			getPopupWindowInstance();
			mPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
			break;
		case R.id.ll_datesbrot:
			// 点击生日
			new DateAlertUtil().timeSelectorBirthday(ActMyDatum.this, tv_brothday, model);
			String tiem = tv_brothday.getText().toString().trim();
			if (!StringUtils.isEmpty(tiem)) {

			}
			break;

		default:
			break;
		}
	}

	private void loadPhotos(int requestCode) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, requestCode);
	}

	/*
	 * PopupWindow
	 */
	private void getPopupWindowInstance() {
		if (null != mPopupWindow) {
			mPopupWindow.dismiss();
			mPopupWindow = null;
			mWL.alpha = 1;
			getWindow().setAttributes(mWL);
			return;
		} else {
			mWL.alpha = 0.5f; // 0.0-1.0
			getWindow().setAttributes(mWL);
			initPopuptWindow();
		}
	}

	/*
	 * PopupWindow
	 */
	private void initPopuptWindow() {
		mScreenWidth = getWindowManager().getDefaultDisplay().getWidth();
		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.popup_window, null);

		mPopupWindow = new PopupWindow(popupWindow, mScreenWidth - 80,DensityUtil.dip2px(this, 200));
		mPopupWindow.setFocusable(true);
		// mPopupWindow.setWindowLayoutMode((mScreenWidth-mPopupWindowWidth)/2, mScreenHeight-mPopupWindowHeight);
		TextView popup_dismiss = (TextView) popupWindow.findViewById(R.id.tv_popup_dismiss);
		TextView popup_load = (TextView) popupWindow.findViewById(R.id.tv_load);
		TextView popup_camera = (TextView) popupWindow.findViewById(R.id.tv_photo);
		popup_dismiss.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getPopupWindowInstance();
			}
		});
		popup_load.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 相册
				getPopupWindowInstance();
				loadPhotos(10);

			}
		});
		popup_camera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 拍照
				getPopupWindowInstance();
				showActivity(ActPhotoCamera.class, false);

			}
		});
	}

	/**
	 * 设置控件value
	 */
	private void setVal() {
		String avatarUrl = model.getAvatarUrl();
		String nickName = model.getNickName();
		gender = model.getGender();

		int userLevel = model.getUserLevel();
		int integral = model.getIntegral();
		ImageLoader imageLoader = new ImageLoader(ActMyDatum.this, R.drawable.bg_head_def);
		imageLoader.loadImage(avatarUrl, iv_photo);
		tv_name.setText(nickName);
		if(model.getEmail() != null){
			tv_email.setText(model.getEmail()); 
		}
		setSex(gender);
		String birth = model.getBirthday();
		if (!StringUtils.isEmpty(birth)) {
			String text = new DateAlertUtil().getDateStr(birth);
			tv_brothday.setText(text);
		}
		tv_type.setText(userLevel + "");
		tv_num.setText(integral + "");
		// 标签处理
		if (model.getUserTags() != null && model.getUserTags().size() > 0) {
			setTagUi(model.getUserTags());
		} else {
			doUserTag();
		}
	}

	private void doUserUp() {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpParams = new HttpParams();
		httpParams.put("token", model.getToken());
		httpParams.put("gender", gender);
		httpParams.put("nickName", tv_name.getText().toString());
		httpParams.put("email", tv_email.getText().toString());

		httpParams.put("qqOpenId", 0);
		httpParams.put("sinaOpenId", 0);
		
		httpParams.put("userTags", mTagsArray);
		httpParams.put("birthday", model.getBirthday());
		httpParams.put("haveImg", 0);
		client.post(HttpUrl.getUrl(HttpUrl.UPDATEUSERINFO), httpParams, new HttpCallBack() {
			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				dismissWaitingDialog();
				if (!StringUtils.isEmpty(arg1)) {
					Toast.makeText(ActMyDatum.this, arg1, Toast.LENGTH_LONG).show();
				}
			}

			@Override
			public void onHttpStarted() {
				showWaitingDialog();
			}

			@Override
			public void onHttpSuccess(Object arg0) {
				dismissWaitingDialog();
				BaseEntity entity = (BaseEntity) arg0;
				if (null != entity) {
					if (entity.getState() == 1) {
						Toast.makeText(ActMyDatum.this, "保存成功", Toast.LENGTH_LONG).show();
						model.setGender(gender);
						model.setNickName(tv_name.getText().toString());
						model.setEmail(tv_email.getText().toString());
						ShareCookie.saveUserInfo(model);
					} else {
						Toast.makeText(ActMyDatum.this, entity.getMessage(), Toast.LENGTH_LONG)
								.show();
					}
				}

			}

		}, BaseEntity.class);
	}

	private void doUserTag() {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpParams = new HttpParams();
		httpParams.put("token", model.getToken());
		httpParams.put("version", "1.0");
		client.get(HttpUrl.getUrl(HttpUrl.USERTAGS), httpParams, new HttpCallBack() {
			public void onHttpFailure(Exception arg0, String arg1) {
				dismissWaitingDialog();
				if (!StringUtils.isEmpty(arg1)) {
					Toast.makeText(ActMyDatum.this, arg1, Toast.LENGTH_LONG).show();
				}
			}

			@Override
			public void onHttpStarted() {
				showWaitingDialog();
			}

			@Override
			public void onHttpSuccess(Object arg0) {
				dismissWaitingDialog();
				UserTagEntity entity = (UserTagEntity) arg0;
				ArrayList<UserTagModel> data = entity.getData();
				if (data != null && data.size() > 0) {
					model.setUserTags(data);
					// 重新储存
					ShareCookie.saveUserInfo(model);
					setTagUi(data);
				}
			}
		}, UserTagEntity.class);
	}

	// 更新标签
	private void setTagUi(ArrayList<UserTagModel> data) {
		if (adapter == null) {
			int count = data.size() >=12 ? 12 : data.size();
			adapter = new DatumTagAdapter(ActMyDatum.this, data , count);
			ml_listview.setAdapter(adapter);
			ml_listview.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					startActivityForResult(new Intent(ActMyDatum.this, ActHotWord.class), 100);
				}
			});
		} else {
			adapter.setData(data);
			adapter.notifyDataSetChanged();
		}
	}

	// 性别
	private void setSex(int gender) {
		switch (gender) {
		case 0:
			tv_man.setBackgroundResource(R.drawable.bg_sex_man);
			tv_man.setTextColor(getResources().getColor(R.color.c_blue2));
			tv_girl.setBackgroundResource(R.drawable.bg_sex_woman);
			tv_girl.setTextColor(getResources().getColor(R.color.font_red));
			break;
		case 1:
			tv_man.setBackgroundResource(R.drawable.bg_sex_man_select);
			tv_man.setTextColor(getResources().getColor(R.color.font_white));
			tv_girl.setBackgroundResource(R.drawable.bg_sex_woman);
			tv_girl.setTextColor(getResources().getColor(R.color.font_red));
			break;
		case 2:
			tv_man.setBackgroundResource(R.drawable.bg_sex_man);
			tv_man.setTextColor(getResources().getColor(R.color.c_blue2));
			tv_girl.setBackgroundResource(R.drawable.bg_sex_woman_select);
			tv_girl.setTextColor(getResources().getColor(R.color.font_white));
			break;

		default:
			break;
		}
	}

	private void doGetUserInfo() {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams params = new HttpParams();
		params.put("token", "");
		// client.setmToken(ShareCookie.getToken());
		client.get(HttpUrl.getUrl(HttpUrl.USERINFO), params, new HttpCallBack() {
			@Override
			public void onHttpSuccess(Object arg0) {
				UserInfoEntity entity = (UserInfoEntity) arg0;
				model = entity.getData();
				setVal();
			}

			@Override
			public void onHttpStarted() {

			}

			@Override
			public void onHttpFailure(Exception arg0, String arg1) {

			}
		}, UserInfoEntity.class);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (200 == resultCode) { 
			model = (UserModel)data.getSerializableExtra("usermodel");
			ArrayList<UserTagModel> tagModels = model.getUserTags();
			int count = tagModels.size() >=12 ? 12 : tagModels.size();
			adapter = new DatumTagAdapter(ActMyDatum.this, model.getUserTags() , count);
			ml_listview.setAdapter(adapter);
			ml_listview.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					startActivityForResult(new Intent(ActMyDatum.this, ActHotWord.class), 100);
				}
			});
		}
		if (data != null && resultCode == Activity.RESULT_OK) {
			Bitmap cameraBitmap = (Bitmap) data.getExtras().get("data");

			getPopupWindowInstance();
			String name = "/"
					+ DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
					+ ".png";
			FileOutputStream fout = null;
			File file = new File("/sdcard/t-gogo/");
			file.mkdirs();
			String filename = file.getPath() + name;
			try {
				fout = new FileOutputStream(filename);
				cameraBitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					fout.flush();
					fout.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			doUploadImg(filename, cameraBitmap);

			// Uri uri = data.getData();
			// String [] proj={MediaStore.Images.Media.DATA};
			// Cursor cursor = managedQuery( uri,
			// proj, // Which columns to return
			// null, // WHERE clause; which rows to return (all rows)
			// null, // WHERE clause selection arguments (none)
			// null); // Order-by clause (ascending by name)
			//
			// int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			// cursor.moveToFirst();
			//
			// String path = cursor.getString(column_index);
			// Bitmap bmp = BitmapFactory.decodeFile(path);
			// iv_photo.setImageBitmap(bmp);
			// getPopupWindowInstance();
			// System.out.println("the path is :" + path);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void doUploadImg(String filename, final Bitmap bitmap) {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpParams = new HttpParams();
		httpParams.put("token", model.getToken());
		httpParams.put("file", new File(filename));
		client.post(HttpUrl.getUrl(HttpUrl.UPLOADAVATAR), httpParams, new HttpCallBack() {
			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				ToastUtils.showMessage("头像上传失败");
			}

			@Override
			public void onHttpStarted() {
				showWaitingDialog();
			}

			@Override
			public void onHttpSuccess(Object arg0) {
				dismissWaitingDialog();
				ToastUtils.showMessage("头像上传成功");
				iv_photo.setImageBitmap(bitmap);
				System.out.println(arg0);
			}
		});
	}
}
